package com.dh.leetcode.k1;

import org.junit.Assert;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName: _1002_find_common_characters
 * @Description: 1002. 查找共用字符
 * 给你一个字符串数组 words ，请你找出所有在 words 的每个字符串中都出现的共用字符（ 包括重复字符），并以数组形式返回。你可以按 任意顺序 返回答案。
 *
 *
 * 示例 1：
 *
 * 输入：words = ["bella","label","roller"]
 * 输出：["e","l","l"]
 * 示例 2：
 *
 * 输入：words = ["cool","lock","cook"]
 * 输出：["c","o"]
 *
 *
 * 提示：
 *
 * 1 <= words.length <= 100
 * 1 <= words[i].length <= 100
 * words[i] 由小写英文字母组成
 *
 * https://leetcode-cn.com/problems/find-common-characters/
 *
 * @Author: shouzimu
 * @Date: 2022/2/8 8:59
 */
public class _1002_find_common_characters {

    public List<String> commonChars(String[] words) {
        int[] bucket = new int[26];
        for (int i = 0; i < words[0].length(); i++) {
            bucket[words[0].charAt(i) - 'a']++;
        }

        for (int i = 1; i < words.length; i++) {
            int[] b2 = new int[26];
            for (int j = 0; j < words[i].length(); j++) {
                b2[words[i].charAt(j) - 'a']++;
            }
            boolean allZero = true;
            for (int k = 0; k < 26; k++) {
                if (bucket[k] > 0) {
                    if (b2[k] < bucket[k]) {
                        bucket[k] = b2[k];
                    }
                    allZero = false;
                }
            }
            if (allZero) {
                break;
            }
        }

        List<String> res = new ArrayList<>();
        for (int i = 0; i < 26; i++) {
            while (bucket[i] > 0) {
                res.add(String.valueOf((char) (i + 'a')));
                bucket[i]--;
            }
        }
        return res;
    }

    @Test
    public void commonCharsTest() {
        Assert.assertEquals(commonChars(new String[]{"bella", "label", "roller"}).stream().collect(Collectors.joining(",")), "e,l,l");
    }
}
